import PySimpleGUI as sg
import random
from string import ascii_letters, ascii_lowercase, ascii_uppercase


def pwd_gui(win_main):
    win_main.Hide()
    sg.theme('LightBlue3')
    layout_pwd = [
        [sg.Text('密码长度：', font=("宋体", 10)),
         sg.Spin([i for i in range(6, 31)], initial_value=6, key='len_range', visible=True,
                 size=(6, 2))],
        [sg.Checkbox('数字', key='num', font=("宋体", 10), default=True),
         sg.Checkbox('小写字母', key='lowercase', font=("宋体", 10)),
         sg.Checkbox('大写字母', key='uppercase', font=("宋体", 10)), sg.Checkbox('特殊字符', key='sc', font=("宋体", 10))],
        [sg.Button('生成密码', key='get_pwd', font=("宋体", 10)), sg.InputText('', font=("宋体", 10), key='pwd_content')],
        [sg.Button('返回', key='back_pwd', font=("宋体", 15))]
    ]
    win_pwd = sg.Window('随机密码生成', layout_pwd, font=("宋体", 15))

    while True:
        ev_pwd, vals_pwd = win_pwd.Read()
        if ev_pwd is None or ev_pwd == 'back_pwd':
            win_pwd.close()
            win_main.UnHide()
            break
        print(ev_pwd, vals_pwd)
        if ev_pwd == 'get_pwd':
            try:
                pwd = create_pwd(int(vals_pwd['len_range']), vals_pwd['lowercase'], vals_pwd['uppercase'],
                                 vals_pwd['num'],
                                 vals_pwd['sc'])
                win_pwd['pwd_content'].update(value=pwd)
            except:
                pass

            # try:
            #     if pwd != '':
            #         win_pwd['pwd_content'].update(value=pwd)
            # except:
            #     pass
            # if pwd == '':
            #     win_pwd['pwd_content'].update(value='选项为空')
            # else:
            #     win_pwd['pwd_content'].update(value=pwd)


def create_pwd(n: int, lowercase=False, uppercase=False, num=False, sc=False):
    str_data = ''
    l = len(str_data)
    try:
        while l < n:
            if num == True:
                str_data += f'{random.randint(0, 9)}'
            l = len(str_data)
            if l == n:
                break
            if lowercase == True:
                str_data += random.choice(ascii_lowercase)
            l = len(str_data)
            if l == n:
                break
            if uppercase == True:
                str_data += random.choice(ascii_uppercase)
            l = len(str_data)
            if l == n:
                break
            if sc == True:
                str_data += random.choice("!@#$%^&*()_-<>?{}[]/,.;':?")
            l = len(str_data)
            if l == n:
                break
    except:
        pass
    return str_data